﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using it_security_project.App_Code.BusinessLogicLayer;
using it_security_project.App_Code;

namespace it_security_project
{
    public partial class Register : System.Web.UI.Page
    {
        private const string ValidationGroup = "RegisterValidation";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GenerateCaptcha();
            }
        }

        public new Site site { get { return base.Master as Site; } }

        private Captcha c;
      

        protected override void OnInit(EventArgs e)
        {
            Member member = site.LoginWithSession();

            if (member != null) // User is NOT logged in
            {
                Response.Redirect("~/Default.aspx");
            }      
        }

        private void GenerateCaptcha()
        {
            c = new CaptchaGenerator().GetCaptcha();        

            ImageCaptacha.ImageUrl = c.ImageURL;
            FUUUSK.Text = c.Name;
        }

        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            string username = UsernameTextBox.Text;
            string password = PasswordTextBox.Text;
            string repeatPassword = RepeatPasswordTextBox.Text;
            string EmailAdress = EmailTextBox.Text;
            string securityQuestion = SecurityQuestionTextbox.Text;
            string securityQuestionAnswer = SecurityQuestionAnswerTextbox.Text;

           
            if (password == repeatPassword)
            {
                try
                {
                    Service service = new Service();
                    Member registerMember = new Member(username, password, repeatPassword, EmailAdress, securityQuestion, securityQuestionAnswer);
                    if (TextBoxCaptcha.Text.ToLower() == FUUUSK.Text.ToLower())
                    {
                        service.RegisterUser(registerMember);
                        Response.Redirect("~/Login.aspx?message=registersuccess");
                    }
                    else
                    {
                        PageExtensions.AddErrorMessage(this, "Captcha is wrong.", ValidationGroup);
                    }
                }
                catch (Exception)
                {
                    PageExtensions.AddErrorMessage(this, "An Error occured when registering user.", ValidationGroup);
                }
            }
            else
            {
                throw new ArgumentException("Passwords doesn't match!!");

            }           
        }
    }
}